package com.hong.base;

import org.redisson.Redisson;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;

import java.util.concurrent.TimeUnit;

public class RedisRLock {

    public static RLock getRLock(Redisson redisson,String key){
        return redisson.getLock(key);
    }

    /**
     * 获取读写锁
     * @param redisson
     * @param key
     * @return
     */
    public static RReadWriteLock getRReadWriteLock(Redisson redisson,String key){
        RReadWriteLock rwlock = redisson.getReadWriteLock(key);
        return rwlock;
    }

    /**
     * 红锁，主要是用于解决集群环境下，单个key的锁，假如key所分配的节点宕机，将导致死锁的问题。
     * 采用的是 一半以上的节点加锁成功 就算成功。
     * @param redisson
     * @param key
     * @return
     */
    public static RedissonRedLock getRRedLock(Redisson redisson,String... key){
        RLock[] rLocks = new RLock[key.length];
        for (int i = 0;i<key.length; i++){
            rLocks[i] = getRLock(redisson,key[i]);
        }
        RedissonRedLock lock = new RedissonRedLock(rLocks);
        return lock;
    }
    /**
     * @param rLock
     * @param lockTime 锁定的最长时间
     * @return
     * @throws InterruptedException
     */
    public static boolean tryLock(RLock rLock,int lockTime) throws InterruptedException {
        return rLock.tryLock(lockTime, TimeUnit.SECONDS);
    }

    /**
     * @param rLock
     * @param waitTime 等待获取锁的最长时间
     * @param lockTime 锁定的最长时间
     * @return
     * @throws InterruptedException
     */
    public static boolean tryLock(RLock rLock,int waitTime,int lockTime) throws InterruptedException {
        return rLock.tryLock(waitTime,lockTime, TimeUnit.SECONDS);
    }
}
